package com.example.controller;


import com.example.common.lang.Result;
import com.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.example.controller.BaseController;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 公众号：java思维导图
 * @since 2020-08-04
 */
@Controller
public class PostController extends BaseController {

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/category/{id:\\d*}")
    public String category(@PathVariable(name = "id")Long id){
        request.setAttribute("currentCategoryId", id);
        return "post/category";
    }

    @GetMapping("/post/{id:\\d*}")
    public String detail(@PathVariable(name = "id")Long id){
        request.setAttribute("currentCategoryId", id);
        return "post/detail";
    }

    @ResponseBody
    @RequestMapping("/post/hots")
    public Result hotPost(){
        Set<ZSetOperations.TypedTuple> lastWeekRank = redisUtil.getZSetRank("last_week_rank", 0, 6);
        List<Map<String, Object>> hotPosts = new ArrayList<>();
        for (ZSetOperations.TypedTuple typedTuple :
                lastWeekRank) {
            Map<String, Object> map = new HashMap<>();
            map.put("comment_count", typedTuple.getScore());
            map.put("id", redisUtil.hashGet("rank_post_"+typedTuple.getValue(), "post:id"));
            map.put("title", redisUtil.hashGet("rank_post_"+typedTuple.getValue(), "post:title"));
            hotPosts.add(map);
        }
        return Result.sucessed(hotPosts);
    }

}
